package com.example.permissionservice.controller;

import com.example.permissionservice.pojo.Resource;
import com.example.permissionservice.pojo.ResourceParent;
import com.example.permissionservice.service.PermissionService;
import com.myprojects.common.dto.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PermissionController {

    @Autowired
    PermissionService permissionService;

    /**
     * 该方法用于测试映射路径的POST
     */
    @RequestMapping(value = "/perm",method = RequestMethod.POST)
    @ResponseBody
    public Msg testPost(){
        return Msg.succeed();
    }

    /**
     * 该方法用于通过用户id来查询用户拥有的所有资源(权限)
     */
    @Value("${server.port}")
    String port;
    @RequestMapping(value = "/perm",method = RequestMethod.GET)
    @ResponseBody
    public Msg getResourceByUserID(
            @RequestParam(value = "user_id") Integer user_id){//普通
        Msg result ;//要返回的结果
        try {
            //获取该用户拥有的所有资源
            List<Resource> resourceList = permissionService.getResByUserID(user_id);
            List<ResourceParent> resourceParentList = new ArrayList<>();
            Map<String,ResourceParent> resourceParentMap = new LinkedHashMap<>();
            //遍历所有该资源并生成父级标题ResourceParentList
            for(Resource resource:resourceList){
                String parentStr = resource.getResourece_name_parent();
                ResourceParent parent = resourceParentMap.get(parentStr);
                //如果该资源父标题还不存在于resourceParentMap中，说明其不存在，则需要创建ResourceParent
                if(parent==null){
                    parent = new ResourceParent();
                    parent.setTitle(parentStr);
                    parent.addResource(resource);
                    resourceParentMap.put(parentStr,parent);
                    resourceParentList.add(parent);
                }else {//否则其存在，直接调用添加方法
                    parent.addResource(resource);
                }
            }

            //生成返回成功的结果
            result = Msg.succeed();
            //将resourceList加入返回的结果中
            result.addData("resourceParentList",resourceParentList);
            System.out.println(result.getDataMap());
        }catch (Exception e){
            e.printStackTrace();
            result = Msg.failed();
            result.setMsg("服务端处理异常!");
        }
        return result;
    }
}
